package org.jivesoftware.openfire.register;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.jivesoftware.admin.AuthCheckFilter;
import org.jivesoftware.openfire.dynamic.DbDynamicManager;
import org.jivesoftware.openfire.dynamic.DynamicServlet;
import org.jivesoftware.util.ParamUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RegisterServlet extends HttpServlet implements  Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 977701117445392069L;
	private static final Logger log = LoggerFactory.getLogger(RegisterServlet.class);
	private static final ObjectMapper mapper = new ObjectMapper();
	 private static DbRegisterManager registerManager;
	 public void init(ServletConfig config) throws ServletException {
	        super.init(config);
	        AuthCheckFilter.addExclude("plugins/register/getregister");
	        registerManager = DbRegisterManager.getInstance();
	        //avoid authority check     
	    }
	 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	        doPost(request, response);
	    }
	 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
     IOException {
		   response.setCharacterEncoding("utf-8");
	        PrintWriter out = response.getWriter();	
	        String action = ParamUtils.getParameter(request, "action");//first parameter
	      
	         if("alreadyuser".equals(action)){
	        	 
	        	 String groupName = ParamUtils.getParameter(request, "groupName");
	        	 String username = ParamUtils.getParameter(request, "username");
	        	 log.info("groupName:"+groupName);
	        	 log.info("username:"+username);

	        	HashMap<String, Object> rowcount = registerManager.queryAlreadyUser(groupName, username);
	        	 StringWriter writer = new StringWriter();
		         mapper.writeValue(writer, rowcount);
		        replyMessage(writer.toString(), response, out);
	        }
	   }
		private void replyMessage(String message, HttpServletResponse response,
				PrintWriter out) {
			// TODO Auto-generated method stub
			  response.setContentType("text/json");
		        out.println(message);
		        out.flush();
		}
		  @Override
		    public void destroy() {
		        super.destroy();
		        // Release the excluded URL
		        AuthCheckFilter.removeExclude("plugins/register/getregister");
		   
		    }
}
